package com.yanqu.road.dao.impl.channelcenter;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.dao.impl.logic.DbInfoParser;
import com.yanqu.road.dao.impl.logic.ProcessInfoParser;
import com.yanqu.road.entity.servercenter.ChannelServerInfo;
import com.yanqu.road.entity.servercenter.DbInfo;
import com.yanqu.road.entity.servercenter.ProcessInfo;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ChannelServerInfoDaoImpl extends TempDao {

    public ChannelServerInfo getChannelServerInfo(int serverId) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_n_channel_server_list where channelServerId=?";
        try {
            getDb().setConnName(DbNameStrategy.getChannelCenterDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setInt(i++, serverId);
            rs = call.executeQuery();
            if (rs.next()) {
                return parseChannelServerInfo(rs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return null;
    }

    public List<ChannelServerInfo> getAllChannelServerInfo() {
        List<ChannelServerInfo> list = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_n_channel_server_list";
        try {
            getDb().setConnName(DbNameStrategy.getChannelCenterDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                ChannelServerInfo info = parseChannelServerInfo(rs);
                list.add(info);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return list;
    }

    private ChannelServerInfo parseChannelServerInfo(ResultSet rs) throws SQLException {
        ChannelServerInfo info = new ChannelServerInfo();
        int serverId = rs.getInt("channelServerId");
        info.setChannelServerId(serverId);
        ProcessInfo serverInfo = ProcessInfoParser.parsingProcessInfo(rs.getString("channelServerInfo"), serverId);
        info.getProcessInfoList().add(serverInfo);
        DbInfo dataDbInfo = DbInfoParser.parseDbInfo(rs.getString("channelDatabase"));
        if (dataDbInfo != null) {
            info.getDbInfos().add(dataDbInfo);
        }
        return info;
    }

}
